<script lang="ts" setup>
import * as L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import 'leaflet.chinatmsproviders'
import { generateUUID } from '@/utils'
import { useThemeStore } from '@/stores/modules/theme'

const props = defineProps({
  isAutoLoad: {
    type: Boolean,
    default: true
  }
})

const themeStore = useThemeStore()

const uuid = ref('id-' + generateUUID())

const map: any = shallowRef(null)
const loadMap = () => {
  if (map.value) {
    return
  }
  map.value = L.map(uuid.value, {
    minZoom: 5, //最小缩放值
    maxZoom: 18, //最大缩放值
    zoom: 16,
    zoomControl: false,
    attributionControl: false,
    center: [30.65833, 104.065837] //成都天府广场坐标
  })
  map.value.locate({ setView: true, maxZoom: 16 }) //获取当前定位并显示（需要开启https）
  switch (themeStore.themeConfig.mapType) {
    case 'TianDiTu': //天地图
      L.layerGroup([
        // 天地图
        (L.tileLayer as any).chinaProvider('TianDiTu.Normal.Map', {
          key: 'e24f4fc9a96afd500faa9ac9232eb86a' //你的地图key
        }),
        // 天地图注释
        (L.tileLayer as any).chinaProvider('TianDiTu.Normal.Annotion', {
          key: 'e24f4fc9a96afd500faa9ac9232eb86a' //你的地图key
        })
      ]).addTo(map.value)
      break
    case 'GaoDe': //高德
      ;(L.tileLayer as any).chinaProvider('GaoDe.Normal.Map').addTo(map.value)
      break
    default:
      ElMessage.error('地图类型配置错误')
  }
  console.log(`[${uuid.value}]\n地图加载成功[${themeStore.themeConfig.mapType}]`)
}
onMounted(() => {
  if (props.isAutoLoad) loadMap()
})
onUnmounted(() => {
  if (map.value) {
    map.value.remove()
    console.log(`[${uuid.value}]\n地图已卸载`)
  }
})

defineExpose({
  map,
  loadMap
})
</script>

<template>
  <div class="w-[100%] h-[100%]" :id="uuid"></div>
</template>
